//
//  ShoperCarConfirmOrderTableViewController.m
//  EasyToTesco2.0
//
//  Created by 袖手旁觀 on 16/8/4.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "CarConfirmOrderController.h"
#import "ConfirmOrderController.h"
#import "ConfirmView.h"
#import "ShopSecondCell.h"
#import "ConfirmOrderCell.h"

#import "AddressManagerController.h"
#import "OrderPaymentController.h"
#import "ProductInfo.h"
#import "AddressModel.h"
#import "AddressTableViewCell.h"
#import "DefaultAddressModel.h"

@interface CarConfirmOrderController ()<UITableViewDelegate,UITableViewDataSource,ConfirmViewOrderDelagate,ThreeViewControllerDelegate>

{
    NSInteger index;
    AddressModel *address;
    BOOL  judgeAddress;
    NSMutableArray *allProductArray;
    DefaultAddressModel *defaultAddress;
    MBProgressHUD *progressHUD;

    double jzh;
}

@property (nonatomic,strong) UILabel *allPriceLabel;

@property(nonatomic,strong)UITableView *confirmOrderView;



@end

@implementation CarConfirmOrderController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@",self.productArray)
    
    self.title = @"确认订单";
    index = self.productArray.count;
    [self addUI];
    NSLog(@"%@",self.allPrice);
    judgeAddress = NO;
    
    NSLog(@"%@",self.typeString);
    
}

- (void)addUI
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UITableView *confirmOrderView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,WIDTH, HEIGHT * 0.8) style:UITableViewStyleGrouped];
    self.confirmOrderView = confirmOrderView;
    [self.view addSubview:confirmOrderView];
    confirmOrderView.delegate = self;
    confirmOrderView.dataSource = self;
    
    ConfirmView *lastView = [[ConfirmView alloc] initWithFrame:CGRectMake(0,HEIGHT * 0.8,WIDTH,HEIGHT/9)];
    lastView.delegate = self;
    double allprice = self.allPrice.doubleValue;
    lastView.totalPrice.text = [NSString stringWithFormat:@"总价:%.1f",allprice + jzh];
    self.allPriceLabel = lastView.totalPrice;
    [self.view addSubview:lastView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (!address) {
        [self getTacitlyAddressData];
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    NSLog(@"%s",__func__);
    defaultAddress = nil;
    NSLog(@"%@",defaultAddress);
}

- (void)dealloc {
    [progressHUD removeFromSuperViewOnHide];
}

//订单支付
- (void)confirmViewOrderDidClick:(UIButton *)button
{
    //    progressHUD = [MBProgressHUD show:self.view andMessage:nil];
    //    [self.view addSubview:progressHUD];
    
    if(!(address || defaultAddress)) {
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"情选择正确地址" toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [self.view addSubview:hud];
        return;
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *name;
        NSString *phone;
        NSString *province;
        NSString *city;
        NSString *county;
        NSString *_address;
        
        if (address) {
            name = address.name;
            phone = address.phone;
            province = address.province;
            city = address.city;
            county = address.county;
            _address = address.address;
        }
        
        if (defaultAddress) {
            name = defaultAddress.name;
            phone = defaultAddress.phone;
            province = defaultAddress.province;
            city = defaultAddress.city;
            county = defaultAddress.county;
            _address = defaultAddress.address;
        }
        
        NSMutableArray *cartArray = [NSMutableArray array];
        NSMutableArray *goodsNumArray = [NSMutableArray array];
        for (ProductInfo *product in self.productArray) {
            [cartArray addObject:product.id];
            NSString *goodsNumber = [NSString stringWithFormat:@"%ld",product.nums];
            [goodsNumArray addObject:goodsNumber];
        }
        
        NSString *cartString = [cartArray componentsJoinedByString:@","];
        NSString *goodsString = [goodsNumArray componentsJoinedByString:@","];
        NSLog(@"%@",cartString);
        NSLog(@"%@",goodsString);
        
        NSDictionary *params = @{
                                 @"username":USERNAME,
                                 @"business_type":@"shop",
                                 @"cart_id":cartString,
                                 @"good_num":goodsString,
                                 @"name":name,
                                 @"phone":phone,
                                 @"province":province,
                                 @"city":city,
                                 @"county":county,
                                 @"address":_address,
                                 @"invoiceTitle":name,
                                 };
        NSLog(@"%@",params);
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Order/createOrderId" completeBlock:^(id object) {
            NSLog(@"%@",object);
            if(JudgeBackDataCode) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                    [progressHUD hide:YES];
                    OrderPaymentController *OrderPaymentVC = [[OrderPaymentController alloc] init];
                    
                    if (self.typeString.length) {
                        OrderPaymentVC.judgeString = self.typeString;
                    }
                    NSDictionary *dict = object[@"data"];
                    OrderPaymentVC.OrderString = dict[@"oid"];
                    OrderPaymentVC.OrderMonryString = dict[@"totalmoney"];
                    OrderPaymentVC.OrderTitleString = @"商城订单";
                    OrderPaymentVC.orderType = @"3";
                    OrderPaymentVC.OrderDescribeInfo = [NSString stringWithFormat:@"商城订单%@",dict[@"totalmoney"]];
                    [self.navigationController pushForm:self.navigationController pushToAndHidden:OrderPaymentVC];
                });
            } else if ([[NSString stringWithFormat:@"%@",object[@"code"]] isEqual:@"-10"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    MBProgressHUD *hud = [MBProgressHUD showMessage:@"该订单已创建,移步商城订单查询状态" toView:self.view dimBackground:NO AndCompleteBlock:nil];
                    [self.view addSubview:hud];
                });
            } else if ([[NSString stringWithFormat:@"%@",object[@"code"]] isEqualToString:@"-9000"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSDictionary *MessageDict = [object objectForKey:@"message"];
                    
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:MessageDict[@"view"] message:nil preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        MyAccountTableViewController *accountVC = [[MyAccountTableViewController alloc] init];
                        [self.navigationController pushForm:self.navigationController pushToAndHidden:accountVC];
                    }];
                    [alert addAction:SettingAction];
                    
                    
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        
                    }];
                    [alert addAction:cancelAction];
                    
                    [self presentViewController:alert animated:YES completion:nil];
                    
                });
            } else {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    MBProgressHUD *hud = [MBProgressHUD showMessage:[NSString stringWithFormat:@"%@",[object[@"message"] objectForKey:@"view"]] toView:self.view dimBackground:NO AndCompleteBlock:nil];
                    [self.view addSubview:hud];
                });
                
            }
        }];
    });
}

- (void)getTacitlyAddressData {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{@"username":USERNAME} AndMenthodName:@"/api/User/addresDefault" completeBlock:^(id object) {
            NSLog(@"%@",object);
            if (JudgeBackDataCode) {
                NSDictionary *Default = [object objectForKey:@"data"];
                if (Default) {
                    defaultAddress = [[DefaultAddressModel alloc] initWithDictionary:Default error:nil];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.confirmOrderView reloadData];
                    });
                }
            }
        }];
    });
}

#pragma mark>>>>>>>>DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }else{
        return self.productArray.count + 3;
        //        NSLog(@"%ld",self.productArray.count);
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"%ld",self.productArray.count);
    
    if (indexPath.section == 0) {
        
        if (address || defaultAddress) {
            AddressTableViewCell *addressCell = [tableView dequeueReusableCellWithIdentifier:@"address"];
            
            if (addressCell == nil) {
                addressCell = [[AddressTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"address"];
                addressCell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            addressCell.imageView.image = [UIImage imageNamed:@"confirmOrder"];
            addressCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            addressCell.nameLabel.text = [NSString stringWithFormat:@"收货人: %@",address.name];
            addressCell.phoneNumberLabel.text = address.phone;
            
            addressCell.addressLabel.text = [NSString stringWithFormat:@"详细地址: %@%@%@%@",address.province,address.city,address.county,address.address];
            
            if (defaultAddress) {
                addressCell.nameLabel.text = [NSString stringWithFormat:@"收货人: %@",defaultAddress.name];
                
                addressCell.phoneNumberLabel.text = defaultAddress.phone;
                
                addressCell.addressLabel.text = [NSString stringWithFormat:@"详细地址: %@%@%@%@",defaultAddress.province,defaultAddress.city,defaultAddress.county,defaultAddress.address];
            }
            
            return addressCell;
            
        } else {
            
            UITableViewCell *firstCell=[tableView dequeueReusableCellWithIdentifier:@"first"];
            
            if (firstCell==nil) {
                firstCell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"first"];
                firstCell.selectionStyle = UITableViewCellSelectionStyleNone;
                firstCell.textLabel.font = FONT(15);
                firstCell.detailTextLabel.font = FONT(15);
            }
            
            
            firstCell.textLabel.text = @"请填写收货地址";
            firstCell.imageView.image = [UIImage imageNamed:@"confirmOrder"];
            firstCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return firstCell;
        }
        
    } else {
        if (indexPath.row < self.productArray.count) {
            ConfirmOrderCell *confirmOrderCell = [tableView dequeueReusableCellWithIdentifier:@"ConfirmOrder"];
            if (confirmOrderCell == nil) {
                confirmOrderCell = [[ConfirmOrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ConfirmOrder"];
                confirmOrderCell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            /*
             *orderImg;
             *orderName;
             *orderColorSize;
             *orderNumber;
             *orderPrice;
             */
            
            ProductInfo *model = self.productArray[indexPath.row];
            NSString *string = [NSString stringWithFormat:@"%@%@",model.picprex[@"s"],model.picurl];
            [confirmOrderCell.orderImg sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            
            confirmOrderCell.orderName.text = model.title;
            
            NSString *yanse;
            NSString *chima;
            NSString *guige;
            NSString *kouwei;
            NSString *taocan;
            NSString *xinghao;
            
            if (model.yanse.length) {
                yanse = [NSString stringWithFormat:@"颜色:%@",model.yanse];
            } else {
                yanse = @"";
            }
            
            if (model.chima.length) {
                chima = [NSString stringWithFormat:@"尺码:%@",model.chima];
            } else {
                chima = @"";
            }
            
            if (model.guige.length) {
                guige = [NSString stringWithFormat:@"规格:%@",model.guige];
            } else {
                guige = @"";
            }
            
            if (model.kouwei.length) {
                kouwei = [NSString stringWithFormat:@"口味:%@",model.kouwei];
            } else {
                kouwei = @"";
            }
            
            if (model.taocan.length) {
                taocan = [NSString stringWithFormat:@"套餐:%@",model.taocan];
            } else {
                taocan = @"";
            }
            
            if (model.xinghao.length) {
                xinghao = [NSString stringWithFormat:@"型号:%@",model.xinghao];
            } else {
                xinghao = @"";
            }
            
            confirmOrderCell.orderColorSize.text = [NSString stringWithFormat:@"%@ %@ %@ %@ %@ %@",yanse,chima,guige,kouwei,taocan,xinghao];
            
            confirmOrderCell.orderNumber.text = [NSString stringWithFormat:@"数量:%ld",model.nums];
            
            confirmOrderCell.orderPrice.text = [NSString stringWithFormat:@"¥:%@",model.jiage];
            
            return confirmOrderCell;
            
        } else {
            static NSString *identifier= @"ConfirmOrderCell";
            
            UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
            
            if (cell==nil) {
                cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.textLabel.font = FONT(15);
                cell.detailTextLabel.font = FONT(15);
            }
            
            
            //            NSLog(@"%ld",indexPath.row - index);
            //            NSLog(@"%ld",indexPath.row);
            NSArray *arr = @[@"配送方式 : ",@"快递运费 : ",@"价格合计 : "];
            
            cell.textLabel.text = arr[indexPath.row - index];
            
            cell.detailTextLabel.text = @"快递";
            
            if (indexPath.row - index == 1) {
                cell.detailTextLabel.text = @"包邮";
                jzh = 0;
                for (ProductInfo *model in self.productArray) {
                    jzh = jzh + model.jzh.integerValue;
                }
                
                if (jzh == 0) {
                    cell.detailTextLabel.text = @"包邮";
                } else {
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%.0f",jzh];
                }
                
                self.allPriceLabel.text = [NSString stringWithFormat:@"总价:%.1f",jzh + self.allPrice.doubleValue];
                
            }
            
//            if (indexPath.row - index == 2) {
//                
//                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                    NSMutableArray *FeilvArray = [NSMutableArray array];
//                    for (ProductInfo *product in self.productArray) {
//                        if (![product.feilv isEqualToString:@"(null)"]) {
//                            [FeilvArray addObject:product.feilv];
//                        }
//                    }
//                    NSLog(@"%@",FeilvArray);
//                    if (FeilvArray.count) {
//                        NSString *FeilvString = [FeilvArray componentsJoinedByString:@"/"];
//                        
//                        dispatch_async(dispatch_get_main_queue(), ^{
//                            cell.detailTextLabel.text = FeilvString;
//                        });
//                    } else {
//                        dispatch_async(dispatch_get_main_queue(), ^{
//                            cell.detailTextLabel.text = @"暂无费率";
//                        });
//                    }
//                });
//            }
            
            if (indexPath.row - index == 2) {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"总价:%.1f",self.allPrice.doubleValue];
                cell.detailTextLabel.textColor = [UIColor redColor];
            }
            
            cell.textLabel.textColor = [UIColor grayColor];
            
            return cell;
            
        }
        
    }
    
}



#pragma mark>>>>>>>>Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",indexPath.row);
    NSLog(@"%@",self.productArray);
    if (indexPath.section == 0) {
        AddressManagerController *AddressManagerVC = [[AddressManagerController alloc] init];
        AddressManagerVC.delegate = self;
        AddressManagerVC.productArray = self.productArray;
        [self.navigationController pushForm:self.navigationController pushToAndHidden:AddressManagerVC];
    }
}

- (void)addViewController:(AddressManagerController *)addViewContrioller addUser:(AddressModel *)userDict andProductArray:(NSMutableArray *)productArray {
    address = userDict;
    /////
    //    NSLog(@"%@",userDict);
    //    NSLog(@"%@",productArray);
    //    NSLog(@"%@",self.productArray);
    [self.confirmOrderView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==0) {
        if (address || defaultAddress) {
            return HEIGHT/9 + 10;
        } else {
            return HEIGHT/10;
        }
    }else if (indexPath.section == 1 && indexPath.row < self.productArray.count){
        
#warning 为iPhone 7 留后路
        if (iPhone5) {
            return HEIGHT/6;
        }else if (iPhone6){
            return HEIGHT/6.5;
        }else{
            return HEIGHT/7;
        }
        
    }else{
        return HEIGHT/13;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.01;
    }else{
        return 10;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (NSMutableArray *)productArray {
    if (!_productArray) {
        _productArray = [NSMutableArray array];
    }
    return _productArray;
}

@end
